<template>
  <div :class="{'pt10': !isFullText}">
    <div v-show="!isFullText" v-loading="loadWhenInit" element-loading-background="#fff">
      <!--没有备课组资源时展示-->
      <div class="cnupBox" v-if="isEmpty">
        <p class="cnup_txt">备课组共建共享的资源库！</p>
        <tencent-upload
            :customType="1"
            :withDetailForm="true"
            @upload-succ="refreshAfterUpload"
        ></tencent-upload>
      </div>
      <!--有备课组资源时展示-->
      <div v-else="!isEmpty">
        <div class="cnflodName" v-show="currShowFolderInfo">
          <h1 class="elips">备课组资源 &gt; {{currShowFolderInfo ? currShowFolderInfo.title : ''}}</h1>
          <a class="Reback" @click="returnMainList">返回</a>
        </div>
        <!-- 列表显示 begin  -->
        <ul class="cnSeaLi cnSeaLiD">
          <li class="cnkiS01">
            <select class="cnkiselectA" v-model="currSearchConfig">
              <option :value="item.key" v-for="item, index in arrSearchConfig">{{item.name}}</option>
            </select>
          </li>
          <li class="cnkiS02">
            <input class="cnkipitA" placeholder="输入检索词" type="text" maxlength="30" @keyup.enter="dosearch"
                   v-model="currSearchText">
            <input class="bcseabtn fl" type="button" value="搜索" @click="dosearch">
          </li>
        </ul>
        <div class="clearfix">
          <tencent-upload
              :customType="2"
              :withDetailForm="true"
              :parentID="currShowFolderCode"
              @upload-succ="refreshAfterUpload"
              class="fl marR10"
          ></tencent-upload>
<!--          <span class="cnnewflod fl marRnew" @click="folderOper('new')" v-if="!currShowFolderInfo">新建文件夹</span>-->
          <div class="cnki_choice" style="padding-top: 4px;">
            <span class="chr01">
              <ins :class="{mcheck: onlyCatalog, mchecked: !onlyCatalog}" @click="onlyCatalog = !onlyCatalog"></ins>
              仅看本小节的
            </span>
            <span class="chr01">
              <ins :class="{mcheck: onlyMine, mchecked: !onlyMine}" @click="onlyMine = !onlyMine"></ins>
              仅看我的资源
            </span>
          </div>
        </div>
        <!--简单检索-->
        <div class="simpSeaBox">
          <div class="sourseScreen">
            格式：
            <span :class="{current: currSearchExt === 'all'}" @click="currSearchExt = 'all'">不限</span>
            <span v-for="item, index in arrSearchExt"
                  @click="currSearchExt = item.key"
                  :class="{current: currSearchExt === item.key}">{{item.name}}</span>
          </div>
          <div class="sourseScreen">
            标签：
            <span :class="{current: currSearchTag === 'all'}" @click="currSearchTag = 'all'">不限</span>
            <span v-for="item, index in arrSearchTagsShow"
                  @click="currSearchTag = item.keyword"
                  :class="{current: currSearchTag === item.keyword}">{{item.keyword}}</span>
            <em class="cnmoreS" v-if="arrSearchTagsShow.length != arrSearchTags.length && arrSearchTags.length > 5"
                @click="arrSearchTagsShow = arrSearchTags">更多</em>
            <em class="cnmoreSB" v-if="arrSearchTagsShow.length == arrSearchTags.length && arrSearchTags.length > 5"
                @click="arrSearchTagsShow = arrSearchTags.slice(0, 5)">收起</em>
          </div>
          <div class="cnkiSort">
            <span class="fl marR10" v-if="isAddBtn">
              <ins :class="{mchecked: !allChecked, mcheck: allChecked}" @click="allChecked = !allChecked" style="margin-top: 6px;"></ins>
              全选
            </span>
            <div class="caddsoure fl" v-if="isAddBtn">
              <span class="cnfolder" @click="addToCourse">添加到课程</span>
            </div>
            <span class="fr cnkitotal">共<em class="orange">{{totalCount}}</em>条</span>
            <!--<div class="xbSort fr">-->
              <!--排序：-->
              <!--<span class="activeB">相关度</span>-->
              <!--<span class="activeT">时间</span>-->
            <!--</div>-->
          </div>
          <div class="cnkibox" v-loading="loadWhenSearch" v-show="arrResources.length > 0">
            <div>
              <!-- line -->
              <dl class="cnbkList" v-for="item, index in arrResources" :class="{'no-left': !isAddBtn}">
                <dt>
                  <span class="checkbtn" v-if="item._showCheckBtn">
                    <ins :class="{mcheck: item._isChecked, mchecked: !item._isChecked}"
                         @click="item._isChecked = !item._isChecked"></ins>
                  </span>
                  <p>
                    <img :src="item._fileTypeIcon" alt="">
                    <span class="pointer" @click="readOnline(item)">{{item.title}}</span>
                    <img src="../../../assets/images/zhiding.png" class="zdpic" v-if="item._isOnTop"/>
                  </p>
                </dt>
                <dd class="cnbk_line">
                  <p class="fl">
                    <span class="marR10">{{item.uname}}</span>
                    <span class="marR10">{{item._time}}</span>
                    <span>大小：{{item._fileSize}}</span>
                  </p>
                </dd>
                <dd v-if="item._arrTags.length">
                  <ins class="gray">标签：</ins>
                  <p class="cnbkkeyword">
                    <span v-for="tagItem, tagIndex in item._arrTags">{{tagItem}}</span>
                  </p>
                </dd>
                <dd class="cnkiSumary" v-if="0">
                  <!--<p>所属课程：所属课程</p>-->
                </dd>
                <dd class="cnoptDD">
                  <ins class="cnkiread" :title="item._readLabel" v-if="!item._isFolder" @click="readOnline(item)" :style="{'backgroundPosition': item._readLabelBg}">{{item._readLabel}}</ins>
                  <ins class="cnkidown" title="下载" v-if="item._isDownLoad && !item._isFolder" @click="downloadItem(item)">下载</ins>
                  <ins class="cnkiEdit" title="编辑" v-if="item._isMine && !item._isOnTop" @click="editResource(item)">编辑信息</ins>
<!--                  <ins class="cnkimove" title="转移" v-if="item._isMine && !item._isFolder && !item._isOnTop" @click="moveItem(item)">转移</ins>-->
                  <ins class="cnkiDelet" title="删除" v-if="item._isMine && !item._isOnTop" @click="deleteResource(item)">删除</ins>
                  <ins class="cnkizhiding" title="置顶" v-if="item._showTopIcon && !item._isOnTop" @click="sendToTop(item)">置顶</ins>
                  <ins class="cnkizhidingB" title="取消置顶" v-if="item._showTopIcon && item._isOnTop" @click="cancelTop(item)">取消置顶</ins>
                </dd>
              </dl>
            </div>
            <!-- line end -->
            <!--分页，动态修改pageindex也会触发current-change方法-->
            <div class="custom-pagination" v-show="totalCount > pageSize">
              <el-pagination @current-change="searchList" :current-page.sync="pageIndex"
                             :page-size="pageSize" layout="prev, pager, next, jumper" :total="totalCount">
              </el-pagination>
            </div>
          </div>
          <div class="cnkinodata" v-show="arrResources.length === 0">
            <b class="orange">提示：</b>
            <p>没有符合条件的资源!</p>
          </div>
        </div>
      </div>
    </div>
    <div class="fulltext" v-if="isFullText" v-loading="loadWhenInit" element-loading-background="#fff">
      <div class="fullName is-fullscreen">
        <h1 class="elips" :title="currReadReso.title">{{currReadReso.title}}</h1>
        <button class="fullread" @click="cnkiReadFullScreen">全屏阅读</button>
        <a class="Reback" @click="returnReadFullText">返回</a>
      </div>
      <!--全文阅读-->
      <div class="fullcon cnki-read-online"
           :style="{height: containerHeight + 'px'}"
           v-loading="loadWhenIframe"
           element-loading-background="#fff">
        <!--office-->
        <iframe v-if="currReadReso.type == 'onlyOffice' || currReadReso.type == 'tencentVideo'"
                :src="currReadReso.src"
                class="iframe-read" @load="loadIframe" frameborder="0" scrolling="no" allowfullscreen></iframe>
        <!--image-->
        <img v-if="currReadReso.type == 'img'"
             :src="currReadReso.src"
             :alt="currReadReso.title"
             class="read-img" @load="imgLoad">
        <!--audio-->
        <audio v-if="currReadReso.type == 'audio'" controls="controls" preload="none" :src="currReadReso.src"></audio>
        <!--nativevideo-->
        <video v-if="currReadReso.type == 'nativeVideo'" controls="controls" preload="none" :src="currReadReso.src" style="max-width: 100%;max-height: 100%;"></video>
      </div>
    </div>
    <move-to
        :resourceToMove="resourceToMove"
        :foldersList="foldersList"
        :currFolderFromFather="currMoveFolderID"
        v-if="isShowMoveToPop"
        @cancel-moveto="toggleMoveToPop"
        @exec-moveto="execMoveto"
    ></move-to>
    <edit-resource
        v-if="showEditResoPop"
        @cancel-upload="toggleEditResoPop"
        @exec-upload="confirmEditReso"
        :defaultData="currResoData"
    ></edit-resource>
  </div>
</template>

<script>
  import tencentUpload from './tencentUpload';
  import editResource from './editUpload';
  import moveTo from './moveTo';
  import {getFileDownUrl, getTencentIfrSrc} from "../../../core/util";

  const path = require("path");
  // todo 需要注意的问题
  // mchecked 是未选中 mcheck是已选中
  export default {
    name: "prepResource",
    props: {
      containerHeight: {
        type: Number
      },
      isAddBtn: {
        type: Boolean,
        default: false
      }
    },
    components: {
      tencentUpload,
      moveTo,
      editResource
    },
    data() {
      return {
        prefix: globalVar.cnkiFullTextAddr,
        isEmpty: true, // 有没有备课组资源
        pageSize: 7, // 每页展示数
        pageIndex: 1, // 分页的当前页
        sourceLib: "LcEdu", // 备课组资源库
        isShowMoveToPop: false,
        showEditResoPop: false, // 展示编辑资源的弹窗
        resourceToMove: '', // 需要移动的资源
        arrResources: [], // 资源数组，主数据
        totalCount: 0, // 总条数
        currResoData: {}, // 选中要编辑的资源数据
        allChecked: false, // 是否全选

        // 可选择条件和已选的条件
        arrSearchConfig: [], // 左上角的select 可以选择资源搜索的基本条件
        arrSearchTags: [], // 搜索条件 标签 所有的
        arrSearchTagsShow: [], // 搜索条件 标签 展示的
        arrSearchExt: [], // 搜索条件 资源的类型 可选数组
        currSearchConfig: 'title', // 对应左上角select的选中
        currSearchTag: 'all', // 对应的标签栏的选中
        currSearchExt: 'all', // 对应的资源类型的选中
        currSearchText: '', // 用户input的输入
        onlyCatalog: false, // 只看本小节的选中状态
        onlyMine: false, // 只看我上传的选中状态

        loadWhenSearch: false, // 搜索时的loading层
        loadWhenIframe: false, // iframe加载之前的层
        loadWhenInit: true, // init方法返回前的loading层
        isFullText: false, // 是否阅读
        currReadReso: {}, // 当前阅读的对象信息
        foldersList: [], // 文件夹列表
        currMoveFolderID: '', // 当前要移动的文件所在的文件夹id
        currShowFolderInfo: null, // 展示文件夹的信息
        currShowFolderCode: '', // 展示文件夹的code
        sortKey: 'date'
      }
    },
    computed: {},
    watch: {
      /**
       * 监测左上角select的变化
       */
      currSearchConfig() {
        this.dosearch();
      },
      /**
       * 标签栏的变化
       */
      currSearchTag() {
        this.dosearch();
      },
      /**
       * 资源类型的变化
       */
      currSearchExt() {
        this.dosearch();
      },
      /**
       * 只看本小节选项的变化
       */
      onlyCatalog() {
        this.dosearch();
      },
      /**
       * 只看我上传的选项的变化
       */
      onlyMine() {
        this.dosearch();
      },
      /**
       * 全选的变化
       */
      allChecked(newvalue, oldvalue){
        this.toggleAllCheck(newvalue);
      }
    },
    methods: {
      /**
       * 获取url地址，测试环境避开跨域头验证
       * @param url
       * @return {*}
       */
      getUrl(url) {
        if (process.env.NODE_ENV === "development") {// 开发阶段绕过限制
          return `/corsWithHeader${url}`;
        } else {
          return this.prefix + url;
        }
      },
      /**
       * 查询时，获取需要传递的参数对象
       */
      getQueryParams(option) {
        if (option === "init") return {
          source: this.sourceLib,
          pageSize: this.pageSize,
          pageIndex: 1,
          sortKey: this.sortKey,
          key1: `CourseCode|${dataFromFather.courseCode}|false`
        }
        // 需要更多查询参数的时候
        // true是精确查找 false是模糊查找
        let arrParams = []
          , originalObj = {
          source: this.sourceLib,
          pageSize: this.pageSize,
          pageIndex: this.pageIndex,
          sortKey: this.sortKey,
          key1: `CourseCode|${dataFromFather.courseCode}|true`
        };
        if(this.currSearchText){ // 有检索词
          arrParams.push(`AND|${this.currSearchConfig}|${this.currSearchText}|false`);
        }
        if (this.currSearchExt != 'all') { // 选择了资源类型
          arrParams.push(`AND|filetype|${this.currSearchExt}|true`);
        }
        if (this.currSearchTag != 'all') { // 选择了标签
          arrParams.push(`AND|keyword|${this.currSearchTag}|false`);
        }
        if (this.onlyCatalog == true) { // 选中了只看本小节
          arrParams.push(`AND|catalogcode|${dataFromFather.catalogCode}|true`);
        }
        if (this.onlyMine == true) { // 选中了只看我上传的
          arrParams.push(`AND|creator|${dataFromFather.userID}|true`);
        }
        if(this.currShowFolderInfo){ // 在文件夹内
          arrParams.push(`AND|folderId|${this.currShowFolderInfo.rescode}|true`)
        }
        arrParams.forEach((item, index, arr) => {
          let key = "key" + (index + 2);
          originalObj[key] = item;
        });
        return originalObj;
      },
      /**
       * 统一的请求方法
       */
      request({type = "get", url, queryData, cb, errcb}) {
        let axiosPromise = null;
        if (type === "get") {
          axiosPromise = axios.get(url, {
            params: queryData,
            headers: {
              'token': dataFromFather.token
            }
          });
        } else {
          axiosPromise = axios.post(url
            , qs.stringify(queryData)
            , {
              headers: {
                'token': dataFromFather.token
              }
            }
          );
        }
        axiosPromise.then(res => {
          if (res && res.status === 200) {
            cb && cb(res.data);
          } else {
            this.globalShowMsg({msg: "请求出错，请重试！"});
            errcb && errcb();
          }
        }, err => {
          console.log(err);
          this.globalShowMsg({msg: "内部错误，请重试!"});
          errcb && errcb();
        });
      },
      /**
       * 获取初始配置
       */
      getConfig() {
        this.request({
          type: 'get',
          url: this.getUrl("/Api/Search/config/LcEdu"),
          queryData: {
            userid: dataFromFather.userID
          },
          cb: res => {
            // console.log(res);
            if (res && res.Code === 200) {
              let data = res.Data;
              this.arrSearchConfig = data.searchConfig;
              this.arrSearchTags = data.keyWordConfig;
              this.arrSearchTagsShow = this.arrSearchTags.slice(0, 5);
              this.arrSearchExt = data.extTypeConfig;
            } else {
              this.globalShowMsg({msg: "查询备课组资源配置出错，请重试！"});
            }
          }
        })
      },
      /**
       * 初始化方法，每次加载编辑器的首次执行，且只执行一次
       * 无资源时，上传第一个资源会执行，不需要轮询
       * 这个接口在耗时很长的情况下，会出现即使存在资源依然是首次上传的bug
       * 添加loadWhenInit，规避这种情况
       * 获取父页面的数据是异步的，此接口需要用到这些数据，得确保有了数据之后才请求
       * @param isPolling 是否执行轮询
       */
      init(isPolling) {
        let triggerOnce = () => {
          this.request({
            url: this.getUrl("/Api/Search/query"),
            queryData: this.getQueryParams("init"),
            cb: res => {
              // 请求完成，关闭初次的loading层
              this.loadWhenInit = false;
              if (res && res.Code === 200) {
                let data = res.Data || {};
                if (data.Count <= 0) {
                  return this.isEmpty = true; // 还没有备课组资源
                }
                this.isEmpty = false;
                this.totalCount = data.Count;
                this.arrResources = this.processRawData(data.Rows);
              } else {
                this.globalShowMsg({msg: "查询备课组资源出错，请重试！"})
              }
            },
            errcb: () => {
              this.loadWhenInit = false;
            }
          })
        };
        if (isPolling) {
          let interval = setInterval(() => {
            if (Object.prototype.toString.call(window.dataFromFather) === '[object Object]') {
              // 父页面完成传值
              clearInterval(interval);
              triggerOnce();
              this.getConfig();
            }
          }, 1000);
        } else {
          triggerOnce();
        }
      },
      /**
       * 执行搜索
       */
      dosearch() {
        // 确认当前的pageIndex
        if (this.pageIndex != 1) {
          return this.pageIndex = 1;
        }
        this.searchList();
      },
      /**
       * 执行搜索的最终方法，避开了分页的影响
       */
      searchList() {
        this.clearAllCheck();
        this.loadWhenSearch = true;
        this.request({
          url: this.getUrl("/Api/Search/query"),
          queryData: this.getQueryParams(),
          cb: res => {
            this.loadWhenSearch = false;
            // console.log(res);
            if (res && res.Code === 200) {
              let data = res.Data || {};
              this.totalCount = data.Count;
              this.arrResources = this.processRawData(data.Rows);
            } else {
              this.globalShowMsg({msg: "查询备课组资源出错，请重试！"});
              // 如果在文件夹内，置空当前文件夹信息
              this.clearCurrFolderInfo();
            }
          },
          errcb: () => {
            this.loadWhenSearch = false;
            // 如果在文件夹内，置空当前文件夹信息
            this.clearCurrFolderInfo();
          }
        })
      },
      /**
       * 处理后台返回的原始数据
       */
      processRawData(arr, type) {
        arr = arr || [];
        let resArr = [];
        if(type === "folder"){
          // 处理文件夹数组
          for (let item of arr) {
            resArr.push({
              title: item.title,
              rescode: item.rescode
            });
          }
        }else{
          // 处理资源数组
          for (let item of arr) {
            // todo 操作raw返回更好用的
            item._arrTags = item.keyword ? item.keyword.split(";") : [];
            item._time = item.createtime.substring(0, 10).replace(/-/g, "/");
            item._isMine = item.uid == dataFromFather.userID;
            item._isChecked = false;
            item._isFolder = this.isFolder(item);
            item._showCheckBtn = !item._isFolder && this.isAddBtn;
            item._isDownLoad = item.isdownload == 1;
            item._fileSize = window.getProperSize(item.fileSize);
            item._fileTypeIcon = this.getFileTypeIcon(item._isFolder, item.extension);
            // 当前登录人是管理员 && 不是文件夹 && 不在文件夹里
            item._showTopIcon = !!dataFromFather.isAdmin && !item._isFolder && !this.currShowFolderInfo;
            item._isOnTop = item.isTop !== 0;
            item._readLabel = /(doc|xls|pdf|ppt)/i.test(item.extension) ? "阅读" : "查看";
            item._readLabelBg = /(doc|xls|pdf|ppt)/i.test(item.extension) ? "" : "0px -257px";

            resArr.push(item);
          }
        }
        return resArr;
      },
      /**
       * 根据资源类型获取icon地址
       */
      getFileTypeIcon(isfolder, ext) {
        if (isfolder) {
          // 文件夹
          return require("../../../assets/images/sj_zt.png");
        }
        if ("docx".indexOf(ext) >= 0) {
          return require("../../../assets/images/sj_word.png");
        }
        if ("pptx".indexOf(ext) >= 0) {
          return require("../../../assets/images/sj_ppt.png");
        }
        if ("xlsx".indexOf(ext) >= 0) {
          return require("../../../assets/images/sj_xls.png");
        }
        if ("pdf".indexOf(ext) >= 0) {
          return require("../../../assets/images/sj_pdf.png");
        }
        if (/(png|jpg|jpeg|gif|bmp)/i.test(ext)) {
          return require("../../../assets/images/sj_img.png");
        }
        if (this.tencentFormatCheck(ext)) {
          return require("../../../assets/images/sj_video.png");
        }
        if ("epub".indexOf(ext) >= 0) {
          return require("../../../assets/images/sj_epub.png");
        }
        if("mp3".indexOf(ext) >= 0){
          return require("../../../assets/images/sj_audio.png");
        }
      },
      /**
       * 移动资源
       */
      moveItem(item){
        this.toggleMoveToPop(true);
        this.resourceToMove = item.rescode;
        this.currMoveFolderID = this.currShowFolderInfo ?
          this.currShowFolderInfo.rescode : 'root';
        this.request({
          type: 'get',
          url: this.getUrl("/help/LcEdu/folders/" + dataFromFather.courseCode),
          cb: res => {
            if(res && res.Code === 200){
              this.foldersList = this.processRawData(res.Folders, "folder");
            }else{
              this.globalShowMsg({msg: "查询文件夹列表出错！"});
            }
          }
        });
      },
      /**
       * 展示移动到弹窗
       */
      toggleMoveToPop(flag) {
        if(this.isShowMoveToPop === flag) return;
        this.isShowMoveToPop = flag;
      },
      /**
       * 执行移动
       */
      execMoveto(data){
        this.toggleMoveToPop(false);
        this.request({
          type: 'post',
          url: this.getUrl(`/help/LcEdu/foldermove?fromLcRescode=${data.resource}&toFolderRescode=${data.toFolderID}`),
          cb: res => {
            if(res && res.Code === 200){
              this.dosearch();
            }else{
              this.globalShowMsg({type: '移动出错，请重试！'});
            }
          }
        })
      },
      /**
       * 删除资源
       */
      deleteResource(item) {
        // todo 删除内有资源的文件夹
        this.$confirm('确定要删除吗?', '删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.request({
            type: "get",
            url: this.getUrl("/help/LcEdu/delete/" + item.rescode),
            cb: res => {
              if (res && res.Code === 200) {
                this.dosearch();
              } else {
                this.globalShowMsg({msg: '删除资源出错，请重试！'});
              }
            }
          })
        }).catch(() => {
        });
      },
      /**
       * 新建/编辑 文件夹
       */
      folderOper(type, item) {
        let boxTitle;
        if (type === 'new') {
          boxTitle = "新建文件夹";
        } else {
          boxTitle = "编辑文件夹";
        }
        let createFolder = (title) => {
          this.request({
            type: 'post',
            queryData: {
              title: title,//标题
              keyword: '',//关键字，例如:"语文教学;荷塘月色;狗血高中"
              des: "",//描述
              isdownload: 0,//默认0-不可下载 0/1
              openlevel: 1,//默认0-完全私有
              uid: dataFromFather.userID,//用户id
              uname: "",//用户名
              isFolder: 1,//默认0-不是文件夹 0/1
              parentid: "",
              courseCode: dataFromFather.courseCode,
              catalogCode: dataFromFather.catalogCode,
              platformid: 0,//0-hfs集群数据 1-腾讯云数据 2-知网资源 3-第三方等
              fileCode: '',//对应平台资源的唯一标识
            },
            url: this.getUrl("/help/LcEdu/add"),
            cb: res => {
              if (res && res.Code === 200) {
                this.dosearch();
              } else {
                this.globalShowMsg({msg: '写入出错，请重试！'});
              }
            }
          });
        }
        this.$prompt('请输入文件夹名称', boxTitle, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder: '请输入文件夹名称',
          inputValue: item ? item.title : "",
          beforeClose(action, instance, done) {
            // 验证新输入的文件夹名称是否合法
            let newName = instance.$refs.input.currentValue;
            if (action === "confirm") {
              if (!newName) {
                return this.globalShowMsg({msg: '文件夹名称不能为空！', type: 'warning'});
              }
            }
            // 不执行这个方法弹出层关不掉
            done();
          }
        }).then(({value}) => {
          if(type === 'new'){
            createFolder(value);
          }else{
            this.confirmEditReso({
              title: value,
              isdownload: 0,
              openlevel: 1,
              rescode: item.rescode
            });
          }
        }).catch(() => {
        });
      },
      /**
       * 上传成功后的操作
       * @Param objData 上传资源的数据
       */
      refreshAfterUpload(objData) {
        let {uploadData, transData} = objData;
        let paramObj = null;
        if (uploadData.type == "isTencent") {
          paramObj = this.getAddParams({
            title: transData.title,
            tags: transData.tags,
            isdownload: transData.isdownload,
            openlevel: transData.openlevel,
            isFolder: 0,
            platformid: 1,
            fileCode: uploadData.downLoadCode,
            size: uploadData.fileSizeNum,
            mtitle: uploadData.fileName,
            ext: uploadData.ext,
            uri: uploadData.uri,
            parentid: uploadData.parentid
          });
        } else {
          paramObj = this.getAddParams({
            title: transData.title,
            tags: transData.tags,
            isdownload: transData.isdownload,
            openlevel: transData.openlevel,
            isFolder: 0,
            platformid: 0,
            fileCode: uploadData.downLoadCode,
            size: uploadData.fileSizeNum,
            mtitle: uploadData.fileName,
            ext: uploadData.ext,
            parentid: uploadData.parentid
          })
        }
        this.request({
          type: 'post',
          queryData: paramObj,
          url: this.getUrl("/help/LcEdu/add"),
          cb: res => {
            if (res && res.Code === 200) {
              if (this.isEmpty) {
                // 没有数据时上传的第一条数据
                this.init(false);
              } else {
                this.dosearch();
              }
            } else {
              this.globalShowMsg({msg: '写入出错，请重试！'});
            }
          }
        });
      },
      /**
       * 得到/help/LcEdu/add接口的参数
       */
      getAddParams({
                     title
                     , tags
                     , isdownload
                     , openlevel
                     , isFolder
                     , platformid
                     , fileCode
                     , size
                     , mtitle
                     , ext
                     , uri
                     , parentid
                   }) {
        return {
          title: title,//标题
          keyword: tags,//关键字，例如:"语文教学;荷塘月色;狗血高中"
          des: "",//描述
          isdownload: isdownload,//默认0-不可下载 0/1
          openlevel: openlevel,//默认0-完全私有
          uid: dataFromFather.userID,//用户id
          uname: "",//用户名
          isFolder: isFolder,//默认0-不是文件夹 0/1
          // 当前在展示文件夹，就是文件夹内上传文件
          parentid: parentid,
          courseCode: dataFromFather.courseCode,
          catalogCode: dataFromFather.catalogCode,
          //moduleCode:"",
          platformid: platformid,//0-hfs集群数据 1-腾讯云数据 2-知网资源 3-第三方等
          fileCode: fileCode,//对应平台资源的唯一标识
          // 选填
          fileSize: size, // 文件大小
          mtitle: mtitle,//素材对应的名称，如"测试.mp4"
          ext: ext,//素材的拓展名,全部小写,"doc"，"ppt","caj"
          author: "",//素材作者
          contributor: "",//素材所属机构
          summary: "",//素材摘要
          snapshot: "",//快照或者缩略图
          uri: uri || ''
        }
      },
      /**
       * 编辑资源
       */
      editResource(item) {
        if(this.isFolder(item)){
          this.folderOper("edit", item);
        }else{
          this.toggleEditResoPop(true);
          this.currResoData = JSON.stringify({
            arrInputTags: item._arrTags,
            title: item.title,
            openlevel: item.openlevel,
            isdownload: item.isdownload != 0,
            rescode: item.rescode
          });
        }
      },
      /**
       * 打开或关闭资源信息编辑窗
       */
      toggleEditResoPop(flag) {
        if(this.showEditResoPop === flag) return;
        this.showEditResoPop = flag;
      },
      /**
       * 确认编辑资源或文件夹
       */
      confirmEditReso({title, tags = "", isdownload, openlevel, rescode, isTop = 0}) {
        this.request({
          type: "post",
          url: this.getUrl("/help/LcEdu/edit"),
          queryData: {
            title: title,
            keyword: tags,
            isdownload: isdownload,
            openlevel: openlevel,
            rescode: rescode,
            isTop: isTop
          },
          cb: res => {
            if (res && res.Code === 200) {
              // 修改了一个资源或文件夹
              this.toggleEditResoPop(false);
              this.globalShowMsg({msg: "修改成功！", type: "success"})
              this.dosearch();
            } else {
              this.globalShowMsg({msg: '修改资源出错，请重试！'});
            }
          }
        })
      },
      /**
       * 切换全选
       */
      toggleAllCheck(flag) {
        for (let item of this.arrResources) {
          item._isChecked = flag;
        }
      },
      /**
       * 清除全选的状态
       */
      clearAllCheck(){
        this.allChecked = false;
      },
      /**
       * 添加到课程
       */
      addToCourse(){
        let tempArr = [], finalArr = [];
        for (let item of this.arrResources) {
          if(item._isChecked && !item._isFolder){
            // 选中的非文件夹的文件
            tempArr.push(item);
          }
        }
        if(tempArr.length === 0) return this.globalShowMsg({msg: '请选择要添加的资源！', type: 'warning'});
        let loading = this.$loading({
          lock: true,
          text: '添加中，请稍后...'
        });
        for (let item of tempArr) {
          let ext = (item.extension || "").toLowerCase()
            , isTencentReso = item.dataType === 1;
          // 获取资源详情
          this.request({
            url: this.getUrl("/help/LcEdu/fulltext?dbCode=LcEdu&mcode=" + item.mcode),
            cb: res => {
              if (res && res.Code === 200) {
                let data = res.Data || {};
                // console.log(data);
                // 判断资源类型，选择打开方式
                let imgRE = /(png|jpg|jpeg|gif|bmp)/i
                  , officeRE = /(doc|ppt|pdf|xls)/i
                  , audioRE = /mp3/i
                  , videoRE = /(mp4|ogg|webm)/i;
                if(isTencentReso){
                  // 预览的是腾讯云资源
                  finalArr.push({
                    type: "video",
                    name: item.title,
                    ifrSrc: getTencentIfrSrc(data.filecode),
                    resourceID: data.filecode
                  });
                } else if (imgRE.test(ext)) {
                  // 预览的是图片
                  finalArr.push({
                    type: "justImg",
                    name: item.title,
                    src: getFileDownUrl() + data.filecode
                  });
                } else if (officeRE.test(ext)) {
                  // 预览的是office
                  this.request({
                    url: globalVar.onlyOffice + `/api/editor/initget`,
                    queryData: {
                      fileCode: data.filecode,
                      fileName: data.mtitle,
                      userId: dataFromFather.userID,
                      userName: ''
                    },
                    cb: officeRes => {
                      if (officeRes && officeRes.Code === 200) {
                        let type = "embedded";
                        if (ext.indexOf("ppt") >= 0) {
                          type = "desktop";
                        }
                        finalArr.push({
                          type: "onlyoffice",
                          name: item.title,
                          ifrSrc: officeRes.Data.Uri + "&Type=" + type + "&version=" + Math.random().toFixed(5),
                          resourceID: data.filecode,
                          iconType: "office_" + ext.substr(0, 3)
                        });
                        if(finalArr.length === tempArr.length){
                          // 遍历完成
                          this.clearAllCheck();
                          this.toggleAllCheck(false);
                          this.$emit('add-prep-data', finalArr);
                          loading.close();
                        }
                      } else {
                        this.globalShowMsg({msg: '请求onlyoffice地址出错，请重试！'});
                        loading.close();
                      }
                    }
                  });
                } else if(audioRE.test(ext)){
                  // 预览的是音频
                  finalArr.push({
                    type: "nativeaudio",
                    name: item.title,
                    src: getFileDownUrl() + data.filecode
                  });
                } else if(videoRE.test(ext)){
                  // 没开腾讯云的视频
                  finalArr.push({
                    type: "nativevideo",
                    name: item.title,
                    src: getFileDownUrl() + data.filecode
                  });
                } else {
                  this.globalShowMsg({msg: '尝试添加的资源中有未知格式！！'})
                }
                if(finalArr.length === tempArr.length){
                  // 遍历完成
                  this.clearAllCheck();
                  this.toggleAllCheck(false);
                  this.$emit('add-prep-data', finalArr);
                  loading.close();
                }
              } else {
                this.globalShowMsg({msg: "查询资源详情出错，请重试！"});
              }
            }
          });
        }
      },
      /**
       * 在线阅读
       * 有可能点击文件夹
       */
      readOnline(item) {
        if(this.isFolder(item)){
          return this.showFilesInFolder(item);
        }
        let ext = (item.extension || "").toLowerCase()
          , isTencentReso = item.dataType === 1;
        // 获取资源详情
        this.request({
          url: this.getUrl("/help/LcEdu/fulltext?dbCode=LcEdu&mcode=" + item.mcode),
          cb: res => {
            if (res && res.Code === 200) {
              let data = res.Data || {};
              // console.log(data);
              this.isFullText = true;
              this.loadWhenIframe = true;
              // 判断资源类型，选择打开方式
              let imgRE = /(png|jpg|jpeg|gif|bmp)/i
                , officeRE = /(doc|ppt|pdf|xls)/i
                , audioRE = /mp3/i
                , videoRE = /(mp4|ogg|webm)/i;
              if(isTencentReso){
                // 预览的是腾讯云资源
                this.currReadReso = {
                  type: 'tencentVideo',
                  title: data.mtitle, // 或者是 item.title，资源名和用户自己设定的名称
                  src: getTencentIfrSrc(data.filecode)
                }
                this.loadWhenIframe = false;
                return;
              }
              if (imgRE.test(ext)) {
                // 预览的是图片
                this.currReadReso = {
                  type: 'img',
                  title: data.mtitle, // 或者是 item.title，资源名和用户自己设定的名称
                  src: getFileDownUrl() + data.filecode
                }
                return;
              }
              if (officeRE.test(ext)) {
                // 预览的是office
                this.currReadReso = {
                  type: 'onlyOffice',
                  title: data.mtitle, // 或者是 item.title，资源名和用户自己设定的名称
                }
                let conf = {
                  fileCode: data.filecode,
                  fileName: data.mtitle,
                  userId: dataFromFather.userID,
                  userName: '',
                  ext: ext
                }
                this.getOnlyOfficeSrc(conf);
                return;
              }
              if(audioRE.test(ext)){
                // 预览的是音频
                this.currReadReso = {
                  type: 'audio',
                  title: data.mtitle, // 或者是 item.title，资源名和用户自己设定的名称
                  src: getFileDownUrl() + data.filecode
                }
                this.loadWhenIframe = false;
                return;
              }
              if(videoRE.test(ext)){
                // 没开腾讯云的视频
                this.currReadReso = {
                  type: 'nativeVideo',
                  title: data.mtitle, // 或者是 item.title，资源名和用户自己设定的名称
                  src: getFileDownUrl() + data.filecode
                }
                this.loadWhenIframe = false;
                return;
              }
            } else {
              this.globalShowMsg({msg: "查询资源详情出错，请重试！"});
            }
          }
        });
      },
      /**
       * 获取onlyoffice地址
       * @param dataset
       */
      getOnlyOfficeSrc(dataset){
        this.request({
          url: globalVar.onlyOffice + `/api/editor/initget`,
          queryData: {
            fileCode: dataset.fileCode,
            fileName: dataset.fileName,
            userId: dataset.userId,
            userName: dataset.userName
          },
          cb: res => {
            if (res && res.Code === 200) {
              let type = "embedded";
              if (dataset.ext.indexOf("ppt") >= 0) {
                type = "desktop";
              }
              this.$set(this.currReadReso, "src", res.Data.Uri + "&Type=" + type + "&version=" + Math.random().toFixed(5));
            } else {
              this.globalShowMsg({msg: '请求onlyoffice地址出错，请重试！'});
            }
            this.loadWhenIframe = false;
          },
          errcb: () => {
            this.loadWhenIframe = false;
          }
        })
      },
      // 全屏阅读
      cnkiReadFullScreen() {
        let that = this;
        const layer = layui.layer;
        let w = $(window).width();
        let h = $(window).height();
        if(that.currReadReso.type == "img"){
          // 图片的普通全屏打开方式
          return layer.open({
            type: 1,
            title: that.currReadReso.title,
            shade: false,
            maxmin: true, //开启最大化最小化按钮
            area: ['1000px', 0.9 * h + 'px'],
            content: '<img src="' + that.currReadReso.src + '" style="position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);max-width: initial;">'
          });
        }
        if(that.currReadReso.type == "audio"){
          return layer.open({
            type: 1,
            title: that.currReadReso.title,
            shade: false,
            maxmin: true, //开启最大化最小化按钮
            area: ['1000px', 0.9 * h + 'px'],
            content: '<audio src="' + that.currReadReso.src + '" controls="controls" preload="none" style="display: block;margin:0 auto;"></audio>'
          });
        }
        if(that.currReadReso.type == "nativeVideo"){
          return layer.open({
            type: 1,
            title: that.currReadReso.title,
            shade: false,
            maxmin: true, //开启最大化最小化按钮
            area: ['1000px', 0.9 * h + 'px'],
            content: '<video src="' + that.currReadReso.src + '" controls="controls" preload="none" style="display: block;margin:0 auto;max-width: 100%;max-height:100%;"></video>'
          });
        }
        layer.open({
          type: 2,
          title: that.currReadReso.title,
          shade: false,
          maxmin: true, //开启最大化最小化按钮
          area: ['1000px', 0.9 * h + 'px'],
          content: that.currReadReso.src
        });
      },
      /**
       * 展示文件夹里面的文件
       */
      showFilesInFolder(fInfo){
        this.currShowFolderInfo = fInfo;
        this.currShowFolderCode = fInfo.rescode;
        this.dosearch();
      },
      /**
       * 从文件夹列表返回主列表
       */
      returnMainList(){
        this.clearCurrFolderInfo();
        this.dosearch();
      },
      /**
       * 清空当前文件夹信息
       */
      clearCurrFolderInfo(){
        this.currShowFolderInfo = null;
        this.currShowFolderCode = '';
      },
      /**
       * 阅读区域返回
       */
      returnReadFullText() {
        this.isFullText = false;
        this.resetCurrReadReso();
      },
      /**
       * 置空当前阅读的对象
       */
      resetCurrReadReso() {
        this.currReadReso = {};
      },
      /**
       * iframe加载之后的操作
       */
      loadIframe() {

      },
      /**
       * 图片加载之后
       */
      imgLoad() {
        this.loadWhenIframe = false;
      },
      /**
       * 下载资源
       */
      downloadItem(item) {
        if(this.tencentFormatCheck(item.extension)){
          // 腾讯云视频
          // console.log(item);
          window.open(item.uri, "_blank");
        }else{
          this.request({
            url: this.getUrl("/help/LcEdu/fulltext?dbCode=LcEdu&mcode=" + item.mcode),
            cb: res => {
              if (res && res.Code === 200) {
                let ifr = document.createElement("iframe");
                ifr.style.display = "none";
                document.body.appendChild(ifr);
                ifr.src = getFileDownUrl() + res.Data.filecode;
              } else {
                this.globalShowMsg({msg: "查询资源详情出错，请重试！"});
              }
            }
          });
        }
      },
      /**
       * 判断一个资源是否是文件夹
       * @param item
       * @return {boolean}
       */
      isFolder(item){
        return item.isfolder === 1;
      },
      /**
       * 置顶
       * @param item
       */
      sendToTop(item){
        this.confirmEditReso({
          title: item.title,
          tags: item.keyword,
          isdownload: item.isdownload,
          openlevel: item.openlevel,
          rescode: item.rescode,
          isTop: 1
        });
      },
      /**
       * 取消置顶
       * @param item
       */
      cancelTop(item){
        this.confirmEditReso({
          title: item.title,
          tags: item.keyword,
          isdownload: item.isdownload,
          openlevel: item.openlevel,
          rescode: item.rescode,
          isTop: 0
        });
      }
    },
    created() {
    },
    mounted() {
      this.init(true);
    }
  }
</script>

<style scoped>
  .cnupBox {
    text-align: center;
    margin: 80px auto 20px;
  }

  .cnup_txt {
    color: #666;
    font-size: 14px;
    margin-bottom: 10px;
  }

  .cnSeaLiD {
    padding: 0px;
  }

  select.cnkiselectA, select.cnkiselectB {
    width: 100%;
    box-sizing: border-box;
    height: 24px;
    padding-left: 0px;
    line-height: 24px;
    border: 1px solid #ccc;
    vertical-align: middle;
  }

  .sourseScreen {
    color: #666;
    font-size: 12px;
    line-height: 30px;
  }

  .sourseScreen span:hover {
    color: #42a5f5;
  }

  .sourseScreen span.current {
    background-color: #42a5f5;
    line-height: 18px;
    color: #fff;
    padding: 0px 5px;
    border-radius: 2px;
  }

  .sourseScreen span {
    display: inline-block;
    margin: 0px 5px;
    cursor: pointer;
  }

  .cnki_choice span.chr01 {
    display: inline-block;
    margin-right: 9px;
    font-size: 12px;
  }

  .cbeike {
    margin-left: 10px;
  }

  .myReturn, .myWrite, .myModify, .myDelete, .myUpload, .myDownload, .myShare, .myUp, .myDown, .myAdd01, .myAdd02, .myLeft, .myRight, .myRead, .myzhiding, .myzhidingB, .Xmove, .Xup {
    display: inline-block;
    width: 18px;
    height: 18px;
    border: 1px solid rgba(255, 255, 255, 0);
    text-indent: -999px;
    overflow: hidden;
    position: relative;
    vertical-align: middle;
    background: url(../../../assets/images/iconS.png) no-repeat 0px 0px;
    cursor: pointer;
  }

  .Xmove {
    background-position: -45px -64px;
  }

  .myDelete {
    background-position: -46px -1px;
  }

  .myReturn:hover, .myWrite:hover, .myModify:hover, .myDelete:hover, .myUpload:hover, .myDownload:hover, .myShare:hover, .myUp:hover, .myDown:hover, .myAdd01:hover, .myAdd02:hover, .myLeft:hover, .myRight:hover, .myRead:hover, .myzhiding:hover, .myzhidingB:hover, .Xmove:hover, .Xup:hover {
    border: 1px solid #c8e0f0;
    padding: 0px;
    background-color: rgba(255, 255, 255, .5);
  }

  .cnfolder {
    border: 1px solid #bad5e9;
    display: inline-block;
    height: 22px;
    line-height: 22px;
    color: #2a8cd7;
    padding: 0px 8px;
    margin-left: 5px;
  }

  .xbSort {
    float: right;
    color: #666;
  }

  .cnkibox {
    margin-top: 8px;
  }

  .cnbkList {
    position: relative;
    padding: 5px 0px 20px 30px;
    border-bottom: 1px solid #e8e6e7;
  }

  .cnbkList:hover {
    background-color: #edf4f8;
  }

  .cnbkList:hover .cnbk_opt {
    display: block;
  }
  .cnbkList dt{
    margin-bottom: 5px;
  }
  .cnbk_line {
    height: 20px;
    line-height: 20px;
    color: #777;
  }

  .cnbkList .checkbtn {
    position: absolute;
    left: 3px;
  }
  .cnkiSumary{
    margin-bottom: 5px;
  }
  .cnoptDD {
    display: none;
    position: absolute;
    bottom:0px;
    right: 10px;
  }

  .cnbkList:hover .cnoptDD {
    display: block;
  }

  .cnbkList dd {
    font-size: 12px;
  }

  .cnbk_opt {
    position: absolute;
    right: 0px;
    top: 0px;
    display: none;
  }

  .cnbk_opt ins {
    margin-left: 3px;
  }

  .myzhiding {
    background-position: 1px -100px;
  }

  .myModify {
    background-position: 1px -1px;
  }

  .cnbkkeyword {
    /*background: url(../../../assets/images/cnkey.png) no-repeat 0px 4px;*/
    line-height: 24px;
    color: #7ea0c2;
    /*padding-left: 20px;*/
    display: inline;
  }

  ins.gray {
    color: #999;
    text-decoration: none;
  }

  .cnbkkeyword span {
    margin-right: 10px;
    display: inline-block;
  }

  .fl {
    float: left;
  }

  .cnfolder:hover {
    border: 1px solid #00a4e6;
    cursor: pointer;
    background-color: #e5faff;
  }

  .cnbkList dt:hover {
    color: #2a8cd7;
  }

  .mcheck, .mchecked {
    margin-right: 2px;
    margin-top: 2px;
  }

  .cnkiSort {
    margin-left: 0;
  }

  .custom-pagination {
    text-align: center;
    padding: 12px 0 9px 0;
  }

  .pointer {
    cursor: pointer;
  }

  .pt10 {
    padding-top: 10px;
  }

  .img-read-online {
    margin: 0;
    width: 100%;
    background-color: #fff;
    overflow: auto;
  }

  .marL10 {
    margin-left: 10px;
  }

  .cnkiread, .cnkizwj, .cnkiEdit, .cnkidown, .cnkimove, .cnkiDelet, .cnkizhiding, .cnkizhidingB{
    text-decoration: none;
    font-size: 12px;
    line-height: 24px;
    background: url(../../../assets/images/cnkisoure.png) no-repeat 0px 4px;
    display: inline-block;
    padding-left: 20px;
    color: #999;
    margin: 0px 3px;
    cursor: pointer;
  }

  .cnkizwj {
    background-position: 0px -26px;
  }

  .cnkiEdit {
    background-position: 0px -58px;
  }

  .cnkidown {
    background-position: 0px -156px;
  }

  .cnkimove {
    background-position: 0px -93px;
  }

  .cnkiDelet {
    background-position: 0px -128px;
  }

  .cnkizhiding {
    background-position: 0px -189px;
  }

  .cnkizhidingB {
    background-position: 0px -222px;
  }

  .cnkiread:hover,
  .cnkizwj:hover,
  .cnkiEdit:hover,
  .cnkidown:hover,
  .cnkimove:hover,
  .cnkiDelet:hover,
  .cnkizhiding:hover,
  .cnkizhidingB:hover {
    color: #00a4e6;
    margin-top: -1px;
  }

  .cnkiSort .mchecked, .cnkiSort .mcheck {
    margin-top: 6px;
  }

  .cnmoreS,.cnmoreSB { cursor: pointer; text-decoration: none; color: #00a4e6; font-size: 12px; display: inline-block; background: url(../../../assets/images/cnmoreS.png) no-repeat right 13px; padding-right: 10px;}
  .cnmoreSB { background-position: right -13px;}
  .cnnewflod { border: 1px solid #2a8cd7; border-radius: 1px;  display: inline-block; height: 22px; line-height: 22px; color: #2a8cd7; font-size: 12px; background-color:#ecf9ff; padding:0px 8px;}
  .cnnewflod:hover {  background-color: #00a4e6; background-position:  7px -76px; color: #fff; cursor: pointer; }
  .marRnew {
    margin-right: 30px;
  }
  img.zdpic { vertical-align: top;}
  .cnflodName {
    margin-bottom: 10px;
    border-bottom: 1px solid #e5e5e5;
    height: 32px;
    position: relative;
  }
  .cnflodName h1 {
    font-size: 14px;
    line-height: 32px;
  }
  .no-left {
    padding-left: 5px;
  }
  .read-img {
    width: auto;
    max-height: 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
  }
  .cnki-read-online {
    position: relative;
    text-align: center;
  }
</style>
